package com.cw.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cw.common.method.CommonMethod;
import com.cw.dto.InpatientRegistrationCondition;
import com.cw.dto.LeaveAdviceDTO;
import com.cw.entity.*;
import com.cw.mapper2.CwglInmaininfoMapper;
import com.cw.mapper2.CwglPrepayinMapper;
import com.cw.mapper2.ThisIiInmaininfoMapper;
import com.cw.mapper2.ThisIiPrepayinMapper;
import com.cw.request.BedUggieRequest;
import com.cw.request.PrintHospitalCertificateRequest;
import com.cw.service.*;
import com.cw.util.LocalDateTimeConverter;
import com.cw.util.PageHelperTool;
import com.cw.vo.LeaveAdviceVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * II_住院主表 服务实现类
 * </p>
 *
 * @author smq
 * @since 2021-05-05
 */
@Service
public class ThisIiInmaininfoServiceImpl extends ServiceImpl<ThisIiInmaininfoMapper, ThisIiInmaininfo> implements IThisIiInmaininfoService {

    @Autowired
    private IIaSickbedinfoService iaSickbedinfoService;

    @Autowired
    private CwglInmaininfoMapper cwglInmaininfoMapper;

    @Autowired
    private CwglPrepayinMapper cwglPrepayinMapper;

    @Autowired
    private ThisIiPrepayinMapper thisIiPrepayinMapper;

    /**
     * 根据床位id获取病人就诊号
     *
     * @param bedId
     * @return
     */
    @Override
    public ThisIiInmaininfo getVisitNo(String bedId) {
        ThisIiInmaininfo patientBed = new ThisIiInmaininfo();
        List<ThisIiInmaininfo> patients = baseMapper.selectList(new LambdaQueryWrapper<>(new ThisIiInmaininfo()).eq(ThisIiInmaininfo::getBedNo, bedId));
        if (CollectionUtils.isNotEmpty(patients)) {
            patientBed = patients.get(0);
        }
        return patientBed;
    }

    /**
     * 根据床位ids已登记床位
     *
     * @param bedIds
     * @return
     */
    @Override
    public List<ThisIiInmaininfo> getRegisterBedByBedIds(List<String> bedIds) {
        return baseMapper.selectList(new LambdaQueryWrapper<>(new ThisIiInmaininfo()).in(ThisIiInmaininfo::getBedNo, bedIds));
    }


    /**
     * 根据床位id获取病人详情
     *
     * @param bedId
     * @return
     */
    @Override
    public ThisIiInmaininfo getPatientDetail(String bedId) {
        return getVisitNo(bedId);
    }

    /**
     * 住院登记记录-已登记列表
     *
     * @param condition 查询条件
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author ly
     * @date 2021/5/6 14:20
     */
    @Override
    public Map<String, Object> getThisIiInmaininfoPagination(InpatientRegistrationCondition condition) {
        Map<String, Object> resultMap = new HashMap<>();

        //急诊
        Integer nullPointCheck = condition.getEmergencyCallPageNum();
        if (ObjectUtil.isNotNull(nullPointCheck)) {
            PageHelper.startPage(nullPointCheck, 15);
            condition.setCode("2");
            List<ThisIiInmaininfo> thisIiPrepayins = baseMapper.getThisIiInmaininfos(condition);
            resultMap.put("emergencyCall", thisIiPrepayins);
        }
        condition.setCode(null);
        //门诊查询
        Integer nullPoint = condition.getOutpatientPageNum();
        if (ObjectUtil.isNotNull(nullPoint)) {
            PageHelper.startPage(nullPoint, 15);
            condition.setCode("1");
            List<ThisIiInmaininfo> thisIiPrepayins = baseMapper.getThisIiInmaininfos(condition);
            resultMap.put("outpatient", thisIiPrepayins);
        }
        return resultMap;
    }


    /**
     * 住院证打印
     *
     * @param condition 查询条件
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author xnd
     * @date 2021/10/19
     */
    @Override
    public Map<String, Object> getPrintHospitalCertificate(PrintHospitalCertificateRequest condition) {
        Map<String, Object> resultMap = new HashMap<>();
        List<ThisIiPrepayin> thisprintIiPrepayins = baseMapper.getPrintHospitalCertificate(condition);
        resultMap.put("outpatient", thisprintIiPrepayins);
        return resultMap;
    }


    /**
     * 根据病人id获取病人详情
     *
     * @param preId
     * @param isNotChange
     * @return
     */
    @Override
    public CwglPrepayin getPatient(String preId, String isNotChange) {
        //床位用户是否可转床 0:可以,从电子住院表里面拿
        CwglPrepayin cwglPrepayin = new CwglPrepayin();
        if ("0".equals(isNotChange)) {
            cwglPrepayin = cwglPrepayinMapper.selectById(preId);
        } else {
            CwglInmaininfo thisIiPrepayins = cwglInmaininfoMapper.selectById(preId);
            cwglPrepayin.setName(thisIiPrepayins.getName());
            cwglPrepayin.setSex(thisIiPrepayins.getSex());
            cwglPrepayin.setBirthday(thisIiPrepayins.getBirthday());
            cwglPrepayin.setPacttype(thisIiPrepayins.getPactName());
            cwglPrepayin.setHeight(thisIiPrepayins.getHeight());
            cwglPrepayin.setMari(thisIiPrepayins.getMari());
            cwglPrepayin.setIdenno(thisIiPrepayins.getIdenno());
            cwglPrepayin.setProfession(thisIiPrepayins.getProfCode());
            cwglPrepayin.setCountry(thisIiPrepayins.getCounCode());
            cwglPrepayin.setDist(thisIiPrepayins.getDist());
            cwglPrepayin.setHome(thisIiPrepayins.getHome());
            cwglPrepayin.setHomeTel(thisIiPrepayins.getHomeTel());
            cwglPrepayin.setPaykindCode(thisIiPrepayins.getPaykindCode());
            cwglPrepayin.setWorkName(thisIiPrepayins.getWorkName());
            cwglPrepayin.setLinkmaName(thisIiPrepayins.getLinkmaName());
            cwglPrepayin.setRelative(thisIiPrepayins.getRelaCode());
            cwglPrepayin.setLinkmanTel(thisIiPrepayins.getLinkmanTel());
            cwglPrepayin.setLinkmanAdd(thisIiPrepayins.getLinkmanAdd());
            cwglPrepayin.setDeptName(thisIiPrepayins.getDeptName());
            cwglPrepayin.setNurseCellName(thisIiPrepayins.getNurseCellName());
            cwglPrepayin.setInpatientNo(thisIiPrepayins.getInpatientNo());
            cwglPrepayin.setBedNo(thisIiPrepayins.getBedNo());
            cwglPrepayin.setDiagName(thisIiPrepayins.getDiagName());
            cwglPrepayin.setIfRjbf(thisIiPrepayins.getYnRjsx());
            cwglPrepayin.setPrepayCost(thisIiPrepayins.getPrepayCost());
            cwglPrepayin.setBeizhu(thisIiPrepayins.getRemark());
            cwglPrepayin.setOperCode(thisIiPrepayins.getOperCode());
            cwglPrepayin.setOperDtime(thisIiPrepayins.getOperDtime());
        }
            LeaveAdviceVO leaveAdviceVO = thisIiPrepayinMapper.leaveAdviceGetOne(preId);
            if (leaveAdviceVO!=null){
                cwglPrepayin.setChangeType(leaveAdviceVO.getChangeType());
            }
        return cwglPrepayin;
    }

    /**
     * 入院列表
     * <h3>只查询本系统录入的数据<h3/>
     *
     * @param condition 查询条件
     * @return java.util.Map<com.cw.entity.ThisIiInmaininfo>
     * @author ly
     * @date 2021/07/14 14:38
     */
    @Override
    public Map<String, Object> getHospitalized(InpatientRegistrationCondition condition) {
        Map<String, Object> resultMap = new HashMap<>();
        //门诊查询
        Integer nullPoint = condition.getOutpatientPageNum();
        if (ObjectUtil.isNotNull(nullPoint)) {
            PageHelper.startPage(nullPoint, 15);
            condition.setCode("2");     //这边2就是门诊
            List<ThisIiInmaininfo> hospitalized = baseMapper.getHospitalized(condition);
            resultMap.put("outpatient", hospitalized);
        }
        //急诊查询
        Integer nullPointCheck = condition.getEmergencyCallPageNum();
        if (ObjectUtil.isNotNull(nullPointCheck)) {
            PageHelper.startPage(nullPointCheck, 15);
            condition.setCode("1");     //1就是急诊
            List<ThisIiInmaininfo> hospitalized = baseMapper.getHospitalized(condition);
            resultMap.put("emergencyCall", hospitalized);
        }
        condition.setCode(null);
        return resultMap;
    }

    /**
     * 出院列表
     * <h3>只查询本系统录入的数据<h3/>
     *
     * @param condition 查询条件
     * @return java.util.Map<com.cw.entity.ThisIiInmaininfo>
     * @author ly
     * @date 2021/07/14 15:40
     */
    @Override
    public Map<String, Object> getLeaveHospital(InpatientRegistrationCondition condition) {
        Map<String, Object> resultMap = new HashMap<>();
        //门诊查询
        Integer nullPoint = condition.getOutpatientPageNum();
        if (ObjectUtil.isNotNull(nullPoint)) {
            PageHelper.startPage(nullPoint, 15);
            condition.setCode("2");  //2就是门诊
            List<ThisIiInmaininfo> list = baseMapper.getLeaveHospital(condition);
            resultMap.put("outpatient", list);
        }
        //急诊查询
        Integer nullPointCheck = condition.getEmergencyCallPageNum();
        if (ObjectUtil.isNotNull(nullPointCheck)) {
            PageHelper.startPage(nullPointCheck, 15);
            condition.setCode("1");  //1就是急诊
            List<ThisIiInmaininfo> list = baseMapper.getLeaveHospital(condition);
            resultMap.put("emergencyCall", list);
        }
        condition.setCode(null);
        return resultMap;
    }


    /**
     * @author xnd
     * @since 2021-10-28
     * 床位异动验证，是不是转病区的患者
     */
    @Override
    public PageInfo<BedUggIeCWInfo> getBedUggIeCW(BedUggieRequest request) {
        List<BedUggIeCWInfo> bedUggIeCWList = getBedUggIeSouce(request);
        int pageIndex = request.getPageIndex();
        int pageSize = request.getPageSize();
        return PageHelperTool.excutePageInfo(bedUggIeCWList, pageIndex, pageSize);
    }


    private List<BedUggIeCWInfo> getBedUggIeSouce(BedUggieRequest request) {
        List<BedUggIeCWInfo> HeaderbedPatient =new ArrayList<>();
        //集管床位住院的人
        List<BedUggIeCWInfo> bedUggIeCWList = baseMapper.getBedUggIeCW(request);
        //查询预约,但没有住院的人
        List<BedUggIeCWInfo> notHospitaList = baseMapper.getAppointmentNotHospitalized(request);

        if(request.getPatientType().equals("0"))
        {
            HeaderbedPatient.addAll(bedUggIeCWList);
            HeaderbedPatient.addAll(notHospitaList);
        }
        else if(request.getPatientType().equals("1"))
        {
            HeaderbedPatient.addAll(notHospitaList);
        }
        else if(request.getPatientType().equals("2"))
        {
            HeaderbedPatient.addAll(bedUggIeCWList);
        }
        else
        {

        }

        if(CollectionUtils.isEmpty(HeaderbedPatient))
        {
            return new ArrayList<>();
        }

        if(request.getPatientName()!=null && !request.getPatientName().isEmpty())
        {
            HeaderbedPatient =HeaderbedPatient.stream().filter(t->t.getName().equals(request.getPatientName())).collect(Collectors.toList());
        }

        //List<ThisIaNurseVsDept> nurseVsDeptList = nurseVsDeptService.getNurseVsDeptList();
        Map<String, List<IaSickbedinfo>> JGBedGroup = new HashMap<>();
        //查询集管床位  getIfGy=1 ,getBedWeave=1
        List<IaSickbedinfo> JGBedList = iaSickbedinfoService.getJGBed();
        //科室病区进行分组
        if (CollectionUtils.isNotEmpty(JGBedList)) {
            JGBedGroup = JGBedList.stream().collect(Collectors.groupingBy(t->t.getDeptCode()+"-"+t.getNurseCellCode()));
        }

        CommonMethod methodClass = new CommonMethod();
        for (BedUggIeCWInfo item : HeaderbedPatient) {
            //ThisIaNurseVsDept match = nurseVsDeptList.stream().filter(t -> t.getDeptCode().equals(item.getDeptCode()) && t.getNurseCellCode().equals(item.getNurseCellCode())).findFirst().orElse(null);
            String isTrue = "0";
            String key =String.join("-",item.getDeptCode(),item.getNurseCellCode());
            if (JGBedGroup.containsKey(key)) {
                List<IaSickbedinfo> matchList = JGBedGroup.get(key);
                IaSickbedinfo match = matchList.stream().filter(t -> t.getBedNo().equals(item.getBedNo())).findFirst().orElse(null);
                if (match == null) {
                    isTrue = "1";
                }
            } else {
                isTrue = "1";
            }
            item.setIsBedUggIeBC(isTrue);
            //去除备注三香后面跟的一大串字
            if (item.getBeizhu() != null) {
                String newBeiZhu = new CommonMethod().RemarkExtend(item.getBeizhu());
                item.setBeizhu(newBeiZhu);
            }
            item.setBedNo(methodClass.getBedName(item.getBedNo()));
            if (item.getCreateBy()==null){
                item.setCreateBy("无");
            }

        }

        if (request.getIsBedUggIeBC().equals("0") && !request.getIsBedUggIeBC().isEmpty()) {
            HeaderbedPatient = HeaderbedPatient.stream().filter(t -> t.getIsBedUggIeBC().equals(request.getIsBedUggIeBC())).collect(Collectors.toList());

        } else if (request.getIsBedUggIeBC().equals("1") && !request.getIsBedUggIeBC().isEmpty()) {
            HeaderbedPatient = HeaderbedPatient.stream().filter(t -> t.getIsBedUggIeBC().equals(request.getIsBedUggIeBC())).collect(Collectors.toList());
        }

        return HeaderbedPatient;
    }


    /**
     * @author xnd
     * @since 2021-10-29
     * 床位异动EXCEL打印下载
     */

    @Override
    public void getBedUggIeCWDownLoadExcel(BedUggieRequest request) throws IOException {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        List<BedUggIeCWInfo> bedUggIeCWList = getBedUggIeSouce(request);
        bedUggIeCWList.forEach(item -> {
            if (item.getIsBedUggIeBC().equals("0")) {
                item.setIsBedUggIeBC("否");
            } else if (item.getIsBedUggIeBC().equals("1")) {
                item.setIsBedUggIeBC("是");
            }
            if (item.getYard().equals("1")) {
                item.setYard("三香");
            } else if (item.getYard().equals("2")) {
                item.setYard("浒关");
            }
            if (item.getIfGy().equals("0")){
                item.setIfGy("当前为非集管");
            }else if
            (item.getIfGy().equals("1")){
                item.setIfGy("");
            }
            if (item.getSex().equals("1")){
                item.setSex("男");
            }else if (item.getSex().equals("2")){
                item.setSex("女");
            }
            if (item.getCreateBy()==null){
                item.setCreateBy("无");
            }
            if (item.getPatientTag()!=null) {
                if (item.getPatientTag().equals("2")) {
                    item.setPatientTag("院前准备患者");
                }
                else  if (item.getPatientTag().equals("0")){
                    item.setPatientTag("普通");
                } else  if (item.getPatientTag().equals("1")){
                    item.setPatientTag("日间手术");
                } else  if (item.getPatientTag().equals("3")){
                    item.setPatientTag("疑似新冠");
                }
            }
        });
        String name = String.valueOf(System.currentTimeMillis());
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(name, "UTF-8");
        // 根据用户传入字段  set是删除字段
        Set<String> excludeColumnFiledNames = new HashSet<String>();
        excludeColumnFiledNames.add("deptCode");
        excludeColumnFiledNames.add("nurseCellCode");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx;");
        EasyExcel.write(response.getOutputStream(), BedUggIeCWInfo.class).registerConverter(new LocalDateTimeConverter()).excludeColumnFiledNames(excludeColumnFiledNames).sheet("sheet").doWrite(bedUggIeCWList);

    }

    @Override
    public List<ThisIiInmaininfo> getInBedInfo(List bedList) {
        return baseMapper.getInBedInfo(bedList);
    }


}
